let data = {};
let requestUrl;
let editingId = null;
let stateArray = ["未装备", "装备中"];

function addHandler() {
	requestUrl = "/xingyin/insert";

	$("#score").numberspinner("setValue", 50);

	$("#xingyin_dialog").dialog("open");
}

function editHandler() {
	let rowData = $("#xingyin_list").datagrid("getSelected");

	if (rowData) {
		requestUrl = "/xingyin/updateById";

		$("#id").val(rowData.id);
		$("#forger").textbox("setValue", rowData.forger);
		$("#roleId").combobox("setValue", rowData.roleId);
		$("#score").numberspinner("setValue", rowData.score);
		$("#texiaoId").combobox("setValue", rowData.texiaoId);
		$("#wearStatus").combobox("setValue", rowData.wearStatus);
		$("#categoryId").combobox("setValue", rowData.categoryId);
		$("#durability").numberspinner("setValue", rowData.durability);

		$("#xingyin_dialog").dialog("open");
	} else {
		alertMsg("请选择要修改的记录！", "warning");
	}
}

function attributeHandler() {
	let rowData = $("#xingyin_list").datagrid("getSelected");

	if (rowData) {
		$("#property_list").datagrid("reload", {
			xingyinId: rowData.id
		});

		$("#property_dialog").dialog("open");
	} else {
		unselected();
	}
}

function viewHandler() {
	let rowData = $("#xingyin_list").datagrid("getSelected");

	if (rowData) {
		$("#base_attribute").empty();
		$("#green_attribute").empty();

		ajaxGet("/xingyin_category/selectById", {
			id: rowData.categoryId
		}, function(resp) {
			let data = resp.data;

			$("#xingyin_image").attr("src", data.image);
			$("#xingyin_name").html(data.name);
			$("#xingyin_grade").html(data.grade);

			ajaxGet("/xingyin_type/selectById", {
				id: data.type
			}, function(resp) {
				let data = resp.data;

				ajaxGet("/xingyin_type/selectById", {
					id: data.parentId
				}, function(resp) {
					let result = resp.data;

					$("#xingyin_type").html(result.name);
					$("#xingyin_note").html(result.note);
				}, error);
			}, error);
		}, error);

		ajaxGet("/xingyin_attribute/selectAttributes", {
			xingyinId: rowData.id
		}, function(resp) {
			let data = resp.data;

			if (data && data.length > 0) {
				let attribute1 = "";
				let attribute2 = "";

				for (let i = 0; i < data.length; i++) {
					let attribute = data[i];

					let html = "<span>&emsp;" + attribute.propertyName + "</span>&ensp;"
						+ (attribute.propertyValue > 0 ? "+" : "")
						+ attribute.propertyValue;

					if (attribute.type === 1) {
						attribute1 += html;
					} else if (attribute.type === 2) {
						if (i !== data.length - 1) {
							html += "<br/>";
						}

						attribute2 += html;
					}
				}

				if (attribute1) {
					$("#base_attribute").append(attribute1);
				}
				if (attribute2) {
					$("#green_attribute").append(attribute2);
				}
			}
		}, error);

		if(rowData.texiaoId === 1) {
			$("#xingyin_texiao").hide();
		} else {
			ajaxGet("/xingyin_texiao_category/selectById", {
				id: rowData.texiaoId
			}, function(resp) {
				let data = resp.data;

				$("#texiao").html(data.name);
				$("#xingyin_texiao").show();
			}, error);
		}

		$("#xingyin_score").html(rowData.score);
		$("#xingyin_forger").html(rowData.forger);
		$("#xingyin_durability").html(rowData.durability);

		$("#detail_dialog").dialog("open");
	} else {
		unselected();
	}
}

function deleteHandler() {
	let rowData = $("#xingyin_list").datagrid("getSelected");

	if (rowData) {
		$.messager.confirm("提示", "是否确认删除？", function(bool) {
			if (bool) {
				ajaxPost("/xingyin/deleteById", {
					id: rowData.id
				}, function(res) {
					showMsg(res.message);

					$("#xingyin_list").datagrid("reload");
				}, error);
			}
		});
	} else {
		alertMsg("请选择要删除的记录！", "warning");
	}
}

function computeHandler() {
	let rowData = $("#xingyin_list").datagrid("getSelected");

	if (rowData) {
		ajaxPost("/xingyin/compute", {
			xingyinId: rowData.id
		}, function(resp) {
			showMsg(resp.message);

			$("#xingyin_list").datagrid("reload");
		}, error);
	} else {
		unselected();
	}
}

$(document).ready(function() {

	/**
	 * 角色ID
	 */
	$("#roleId").combobox({
		url: "/role_account/selectAll",
        valueField: "id",
		textField: "name",
		width: 150,
		required: true,
		panelWidth: "auto",
		panelHeight: "auto",
		formatter: function(row) {
			ajaxGet("/role_category/selectById", {
				id: row.categoryId
			}, function(res) {
				let data = res.data;

				$("#role_" + row.id).attr("title", data.name)
					.attr("src", data.image);
			}, error);

			ajaxGet("/school/selectById", {
				id: row.schoolId
			}, function(res) {
				let data = res.data;

				$("#school_" + row.id).attr("title", data.name)
					.attr("src", data.image);
			}, error);

			return "<img height='20' id='role_" + row.id + "' />&ensp;" + row.name
				+ "&ensp;<img height='20' id='school_" + row.id + "' />";
		}
	});

	/**
	 * 穿戴状态
	 */
	fetchSelect("#wearStatus", stateArray, {
		width: 150,
		required: true
	});

	/**
	 * 星印类型
	 */
	$("#categoryId").combobox({
		url: "/xingyin_category/selectAll",
        valueField: "id",
		textField: "name",
		width: 150,
		required: true,
		panelHeight: "auto",
		formatter: function(row) {
			return "<img width='20' src='" + row.image + "' />&nbsp;" + row.name;
		}
	});

	/**
	 * 耐久度
	 */
	$("#durability").numberspinner({
		min: 0,
		width: 150,
		required: true
	});

	/**
	 * 打造者
	 */
	$("#forger").textbox({
		width: 150,
        required: true
    });

	/**
	 * 特效
	 */
	$("#texiaoId").combobox({
		url: "/xingyin_texiao_category/selectAll",
        valueField: "id",
		textField: "name",
		width: 150,
		required: true,
		groupField: "type",
		panelHeight: "auto",
		groupFormatter: function(group) {
			ajaxGet("/xingyin_texiao_type/selectById", {
				id: group
			}, function (res) {
				$("#texiao_type_" + group).html(res.data.name);
			}, error);

			return "<div class='blue' id='texiao_type_" + group + "'></div>";
		}
	});

	/**
	 * 星印评分
	 */
	$("#score").numberspinner({
		min: 50,
		value: 50,
		width: 150,
		required: false
	});

	$("#xingyin_dialog").dialog({
		title: "星印信息",
		width: 500,
		height: 300,
		buttons: [{
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				let selector = "#xingyin_form";

				checkForm(selector, function () {
					let data = $(selector).serialize();

					ajaxPost(requestUrl, data, function(resp) {
						showMsg(resp.message);

						$(selector).form("clear");
						$("#xingyin_dialog").dialog("close");
						$("#xingyin_list").datagrid("reload");
					}, error);
				});
			}
		}, {
			iconCls: "icon-cancel",
			text: "取消",
			handler: function() {
				$("#xingyin_dialog").dialog("close");
				$("#xingyin_form").form("clear");
			}
		}]
	});

	/******************************************************************************************************/

	/**
	 * 星印属性列表
	 */
	$("#property_list").datagrid({
		url: "/xingyin_attribute/selectByPage",
		title: "星印属性列表",
		width: 480,
		height: 300,
		pagination: true,
		pageSize: 5,
		pageList: [5, 10, 20, 50],
		onAfterEdit: function (rowIndex, rowData, changes) { // 结束行内编辑事件
			data = {
				id: rowData.id,
				xingyinId: rowData.xingyinId,
				type: changes.type ? changes.type : rowData.type,
				propertyId: changes.propertyId ? changes.propertyId : rowData.propertyId,
				propertyValue: changes.propertyValue ? changes.propertyValue : rowData.propertyValue
			};
		},
		toolbar: [{
			iconCls: "icon-add",
			text: "添加",
			handler: function() {
				let datagrid = $("#property_list");
				let rowData = $("#xingyin_list").datagrid("getSelected");

				if(rowData) {
					requestUrl = "/xingyin_attribute/insert";

					datagrid.datagrid("appendRow",{
						xingyinId: rowData.id,
						propertyId: "",
						type: "",
						val: 1
					});

					let total = datagrid.datagrid("getRows").length;

					editingId = total - 1;

					datagrid.datagrid("beginEdit", editingId);
				} else {
					unselected("请选择一件星印~");
				}
			}
		}, "-", {
			iconCls: "icon-edit",
			text: "修改",
			handler: function() {
				let datagrid = $("#property_list");

				if (editingId != null) {
					datagrid.datagrid("selectRow", editingId);
				} else {
					let row = datagrid.datagrid("getSelected");

					if (row) {
						// 获取行索引，这个索引从0开始
						let rowIndex = datagrid.datagrid("getRowIndex", row);

						editingId = rowIndex;
						requestUrl = "/xingyin_attribute/updateById";

						datagrid.datagrid("beginEdit", rowIndex);

						let $editor = datagrid.datagrid("getEditor", {
							index: rowIndex,
							field: "propertyId"
						});

						let rowData = $("#xingyin_list").datagrid("getSelected");

						$($editor.target).combobox("reload", {
							xingyinId: rowData.categoryId
						});
					} else {
						unselected();
					}
				}
			}
		}, "-", {
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				if (editingId != null) {
					// 只有结束编辑才能获取到最新的值
					$("#property_list").datagrid("endEdit", editingId);

					ajaxPost(requestUrl, data, function(resp) {
						editingId = null;

						showMsg(resp.message);

						$("#property_list").datagrid("reload");
					}, error);
				}
			}
		}, "-", {
			iconCls: "icon-cancel",
			text: "取消",
			handler: function() {
				if (editingId != null) {
					$("#property_list").datagrid("cancelEdit", editingId);

					editingId = null;
				}
			}
		}, "-", {
			iconCls: "icon-delete",
			text: "删除",
			handler: function() {
				let rowData = $("#property_list").datagrid("getSelected");

				if(rowData) {
					$.messager.confirm("提示", "是否确认删除？", function(bool) {
						if (bool) {
							ajaxPost("/xingyin_attribute/deleteById", {
								id: rowData.id
							}, function(resp) {
								showMsg(resp.message);

								$("#property_list").datagrid("reload");
							}, error);
						}
					});
				} else {
					unselected();
				}
			}
		}],
		columns: [[
			{field: "id", hidden: true},
			{field: "xingyinId", hidden: true},
			{field: "type", title: "属性类型", align: "center", width: 150
				, editor: {
					type: "combobox",
					options: {
						url: "/property_type/selectAll",
						valueField: "id",
						textField: "alias",
						editable: false,
						panelHeight: "auto",
						loadFilter: function (resp) {
							let data = resp.data;

							return data.filter(function (item) {
								return item.alias && item.alias !== "";
							});
						}
					}
				}
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/property_type/selectById", {
						id: value
					}, function(resp) {
						let data = resp.data;

						$("#type_" + rowIndex).html(data.alias);
					}, error);

					return "<div class='blue' id='type_" + rowIndex + "'></div>";
				}
			},
			{field: "propertyId", title: "属性", align: "center", width: 150
				, editor: {
					type: "combobox",
					options: {
						url: "/xingyin_view_attribute/selectByXingyinId",
						valueField: "id",
						textField: "name",
						groupField: "type",
						editable: true,
						panelHeight: "auto"
					}
				}
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/property/selectById", {
						id: value
					}, function(resp) {
						let data = resp.data;

						$("#property_" + rowIndex).html(data.name);
					}, error);

					return "<div class='blue' id='property_" + rowIndex + "'></div>";
				}
			},
			{field: "propertyValue", title: "属性值", align: "center", width: 150, editor: {
					type: "numberspinner",
					options: {
						min: 1,
						editable: true
					}
				}
			}
		]]
	});

	/**
	 * 星印属性对话框
	 */
	$("#property_dialog").dialog({
		title: " ",
		height: 340
	});

	/******************************************************************************************************/

	$("#detail_dialog .splitter").textbox({
		width: 220
	});

	/**
	 * 星印详情对话框
	 */
	$("#detail_dialog").dialog({
		title: " ",
		width: 240
	});

	/******************************************************************************************************/

	/**
	 * 表格体的高度
	 * @type {number}
	 */
	let heigt_body = heigt_tr_with_role_details * 10;
	/**
	 * 表格高度
	 * @type {number}
	 */
	let height_table = heigt_tool + heigt_header + heigt_filter + heigt_body + heigt_footer + heigt_scoll_bar + 2;

	let datagrid = $("#xingyin_list").datagrid({
		url: "/xingyin/selectByPage",
		height: height_table,
		fitColumns: true,
		rownumbers: true,
		pagination: true,
		remoteFilter: true,
		clientPaging: false,
		onHeaderContextMenu: function(e){
			e.preventDefault();

			if (!columnMenu){
				createColumnMenu("#xingyin_list");
			}
			columnMenu.menu("show", {
				left: e.pageX,
				top: e.pageY
			});
		},
		onLoadSuccess: function () {
			let selector = "#xingyin_list";
			let fields = getFields(selector);

			if (fields.length > 0) {
				let datagrid = $(selector);

				for (let i = 0; i < fields.length; i++) {
					let field = fields[i];

					// 隐藏未选中的字段
					if (!field.selected) {
						datagrid.datagrid("hideColumn", field.name);
					}
				}

				datagrid.datagrid("fitColumns");
			}
		},
		toolbar: [{
			iconCls: "icon-add",
			text: "添加",
			handler: function() {
				addHandler();
			}
		}, "-", {
			iconCls: "icon-edit",
			text: "修改",
			handler: function() {
				editHandler();
			}
		}, "-", {
			iconCls: "icon-shield",
			text: "属性",
			handler: function() {
				attributeHandler();
			}
		}, "-", {
			iconCls: "icon-search",
			text: "查看",
			handler: function() {
				viewHandler();
			}
		}, "-", {
			iconCls: "icon-delete",
			text: "删除",
			handler: function() {
				deleteHandler();
			}
		}, "-", {
			iconCls: "icon-ok",
			text: "计算评分",
			handler: function() {
				computeHandler();
			}
		}],
		columns: [[
			{field: "id", hidden: true},
			{field: "categoryId", title: "星印类型", align: "center", width: 160
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/xingyin_category/selectById", {
						id: value
					}, function(resp) {
						let data = resp.data;

						$("#category_" + rowIndex).tooltip({
					        position: "left",
					        content: "<span class='white'>" + data.name + "</span>",
					        onShow: function() {
					    		$(this).tooltip("tip").css({
					    			backgroundColor: "#666",
					    			borderColor: "#666"
					    		});
					        }
					    }).attr({"src": data.image, "alt": data.name});
					}, error);
					
					return "<img height='" + size + "' id='category_" + rowIndex + "' />";
				}
			},
			{field: "texiaoId", title: "特效", align: "center", width: 160
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/xingyin_texiao_category/selectById", {
						id: value
					}, function(resp) {
						let data = resp.data;

						$("#texiao_" + rowIndex).tooltip({
							position: "bottom",
							content: "<span class='white'>" + data.name + "：" + data.note + "</span>",
							onShow: function() {
								$(this).tooltip("tip").css({
									backgroundColor: "#666",
									borderColor: "#666"
								});
							}
						}).html(data.name);
					}, error);
					
					return "<div class='blue' id='texiao_" + rowIndex + "'></div>";
				}
			},
			{field: "forger", title: "打造者", align: "center", width: 160},
			{field: "durability", title: "耐久度", align: "center", width: 160, sortable: true},
			{field: "score", title: "评分", align: "center", width: 160, sortable: true},
			{field: "wearStatus", title: "穿戴状态", align: "center", width: 160
				, formatter: function(value) {
					return "<span>" + stateArray[value] + "</span>";
				}
			},
			roleDetailsColumn
		]]
	});

	datagrid.datagrid("enableFilter", [{
		field: "categoryId",
		type: "combobox",
		options: {
			url: "/xingyin_category/selectAll",
			valueField: "id",
			textField: "name",
			panelHeight: "auto",
			formatter: function(row) {
				return "<img width='20' src='" + row.image + "' />&nbsp;" + row.name;
			}
		},
		operator: ["equal"]
	}, {
		field: "texiaoId",
		type: "combobox",
		options: {
			url: "/xingyin_texiao_category/selectAll",
			valueField: "id",
			textField: "name",
			panelHeight: "auto"
		},
		operator: ["equal"]
	}, {
		field: "roleId",
		type: "combobox",
		options: {
			url: "/role_account/selectAll",
			valueField: "id",
			textField: "name",
			panelHeight: "auto",
			formatter: function(record) {
				ajaxGet("/role_category/selectById", {
					id: record.categoryId
				}, function(resp) {
					let data = resp.data;

					$("#modeling_" + record.id).attr({
						src: data.image,
						title: data.name
					});
				}, error);

				return "<img width='20' id='modeling_" + record.id + "' />&ensp;" + record.name;
			}
		},
		operator: ["equal"]
	}, {
		field: "wearStatus",
		type: "combobox",
		options: {
			data: getJsonData(stateArray),
			panelHeight: "auto"
		},
		operator: ["equal"]
	}]);

});